<template>
  <div class="login-com">
    <el-card class="box-card">
      <el-tabs v-model="activeName" style="margin: auto" @tab-click="handleClick">
        <el-tab-pane label="密码登录" name="first">
          <el-form ref="pwdLoginFrom" :model="pwdLoginFrom" :rules="pwdLoginRules">
            <el-form-item prop="userName">
              <el-input
                  v-model="pwdLoginFrom.userName"
                  type="text"
                  auto-complete="off"
                  placeholder="用户名"
                  prefix-icon="el-icon-user"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="loginPwd">
              <el-input
                  v-model="pwdLoginFrom.loginPwd"
                  type="password"
                  auto-complete="off"
                  placeholder="密码"
                  prefix-icon="el-icon-lock"
                  show-password
              >
              </el-input>
            </el-form-item>

            <el-form-item style="width:100%;">
              <el-button
                  :loading="loading"
                  size="medium"
                  type="primary"
                  style="width:100%;"
                  @click="handleLoginPwd"
              >
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
            </el-form-item>
          </el-form>

        </el-tab-pane>

        <el-tab-pane label="手机号登录" name="second">

          <el-form ref="phoneLoginFrom" :model="phoneLoginFrom" :rules="phoneLoginRules">
            <el-form-item prop="phone" class="">
              <el-input
                  v-model="phoneLoginFrom.phone"
                  type="text"
                  auto-complete="off"
                  placeholder="手机号"
                  prefix-icon="el-icon-user"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="verificationCode">
              <el-input
                  v-model="phoneLoginFrom.verificationCode"
                  auto-complete="off"
                  placeholder="验证码"
                  style="width: 60%;float: left"
                  prefix-icon="el-icon-key"
              >
              </el-input>
              <el-button
                  @click="getVerificationCode"
                  style="width: 35%;float:right;"
                  :disabled="disabled"
              >{{btnTxt}}</el-button>
            </el-form-item>

            <el-form-item style="width:100%;">
              <el-button
                  :loading="loading"
                  size="medium"
                  type="primary"
                  style="width:100%;"
                  @click="handleLoginPhone"
              >
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

      </el-tabs>
      <span>首次使用?</span>&nbsp;
      <router-link to="/register"><el-link type="primary">点我注册</el-link></router-link>

    </el-card>
  </div>
</template>

<script>

import {isMobile} from "@/utils/validate";
import {getVerificationCode} from "@/api/user";

export default {
  name: "index",

  data() {
    let validatePhone = (rule,value,callback)=>{
      if (!value){
        callback(new Error('手机号不能为空'));
      }
      //使用正则表达式进行验证手机号码
      if (!isMobile(value)){
        callback(new Error('请输入正确的手机号码'));
      }
      //自定义校验规则 需要调用callback()函数！
      callback();
    };
    return {
      btnTxt: "获取验证码",
      disabled:false,
      loading:false,
      time: 0,
      activeName:'first',
      pwdLoginFrom:{
        userName: "",
        loginPwd: ""
      },
      phoneLoginFrom:{
        phone: "",
        verificationCode: ""
      },
      pwdLoginRules:{
        userName: [
          {required: true, trigger: "blur", message: "请输入您的账号"}
        ],
        loginPwd: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],

      },
      phoneLoginRules:{
        code: [
          {required: true, trigger: "blur", message: "请输入验证码"}
        ],
        phone:[
          {required: true, trigger: "blur",validator:validatePhone}
        ]
      }
    };
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleLoginPwd(){
      //TODO
      this.$refs.pwdLoginFrom.validate(valid =>{
        if (valid){
          this.loading=true;
          this.$store.dispatch('LoginByPwd',this.pwdLoginFrom).then(()=>{
            console.log("登录成功，跳转主页")
            this.$message({
              message:"登录成功",
              type: 'success'
            })
            //登录成功跳转主页
            this.$router.push("home")
          }).catch(()=>{
            console.log("登录失败")
            this.loading = false;
            this.pwdLoginFrom.loginPwd = '';
          });

        }
      })
    },

    handleLoginPhone(){
      this.$refs.phoneLoginFrom.validate(valid =>{
        if(valid){
          this.loading = true;
          this.$store.dispatch('LoginByPhoneCode',this.phoneLoginFrom).then(()=>{
            this.$message({
              message:"登录成功",
              type: 'success'
            })
            //登录成功跳转主页
            this.$router.push("home")
          }).catch(()=>{
            console.log("登录失败")
            this.loading = false;
            this.phoneLoginFrom.verificationCode = '';
          })
        }
      })
    },
    //获取验证码
    getVerificationCode(){
    //1.校验手机验证码
      if(!this.phoneLoginFrom.phone){
        //手机号校验不通过
        this.$message({
          message: '请输入手机号码',
          type: 'warning'
        });
      }else if (!isMobile(this.phoneLoginFrom.phone)){
        //此处失去焦点后自动触发手机校验柜子
      }else{
        //手机号校验通过
        this.time = 60;
        this.disabled = true;
        this.timer();//调用倒计时方法
        //发送axios请求
        getVerificationCode(this.phoneLoginFrom.phone).then(()=>{
          this.$message({
            message:'验证码发送成功',
            success: 'success'
          })
        });
      }
    },
    //倒计时方法
    timer() {
      if (this.time > 0) {
        this.time--;
        // console.log(this.time);
        this.btnTxt = this.time+ "s";
        setTimeout(this.timer, 1000);
      } else{
        this.time = 0;
        this.btnTxt = "获取验证码";
        this.disabled = false;
      }
    },
  }
}
</script>

<style scoped>
.login-com{
  text-align: center;
}


.box-card {
  width: 400px;
  margin: 50px auto;
  /*height: 500px;*/
  text-align: center;
}
</style>
